﻿using System;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Configuration;
using MimeKit;

namespace GiteeApi.Utils
{
    /// <summary>
    /// 邮箱发送
    /// </summary>
    public class EmailUtil
    {
        private readonly IConfiguration _configuration;

        public EmailUtil(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        // 主机地址
        private const string Host = "smtp.qq.com";
        // 端口
        private const int Port = 465;

        /// <summary>
        /// 发送邮件 - 群发
        /// </summary>
        /// <param name="mail">邮件列表</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        public async Task<bool> SendMail(string[] mail, string title, string content)
        {
            // 邮箱信息实例化
            var message = new MimeMessage
            {
                // 来自谁
                From = { new MailboxAddress("Gitee AccessToken", "n0tssss@qq.com") },
                // 标题
                Subject = title,
                // 内容
                Body = new TextPart("plain") { Text = $"{content}" }
            };

            // 发给谁
            foreach (var item in mail)
            {
                message.To.Add(new MailboxAddress(item, item));
            }

            // 发信服务器配置
            using (var client = new SmtpClient())
            {
                // 邮件服务器配置
                client.Connect(Host, Port, true);
                // 账号密码
                client.Authenticate(_configuration["Mail:UserName"], _configuration["Mail:Password"]);
                // 发送邮件
                await client.SendAsync(message);
                // 释放
                client.Disconnect(true);

                // 打印调试
                Console.WriteLine($"[邮件发送成功]\n标题：{title}\n内容：{content}");

                return true;
            }
        }

        /// <summary>
        /// 发送邮件 - 单发
        /// </summary>
        /// <param name="mail">邮箱</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        public async Task<bool> SendMail(string mail, string title, string content)
        {
            return await SendMail(new[] { mail }, title, content);
        }
    }
}